/**
 * Created by zqk on 2018/5/15.
 */
var currentWorkOrderId = 0;
var workOrderList;
var openId = 0;
$(document).ready(function () {
    var form=new xhForm($('#xh_form'));
    workOrderList= $('#workorderList');
    $('.xh-datagrid-toolbar').parseToolbar();
    $btn_menu=$('#bt_list_state').menubutton({
        iconCls: 'fa fa-bars',
        menu: '#changestatus',
    });
    //设置禁用
    $('#bt_list_edit').setButtonDisable('eu');
    $('#bt_list_del').setButtonDisable('eu');
    $('#bt_list_check').setButtonDisable('eu');
    $('#bt_comments_look').setButtonDisable('eu');

    form.parse();
    form.bindRequired($('#bt_form_add,#bt_form_edit'));//绑定事件

    function progressFormatter(value,rowData,rowIndex){
        htmlstr='<div  class="easyui-progressbar progressbar"  style="width: 150px; line-height: 20px; height: 20px;">'
            +'<div class="progressbar-text" style="width: 150px; height: 20px; line-height: 20px;">'+value+'%</div> '
            +'<div class="progressbar-value" style="width:' +value+'%; height: 20px; line-height: 20px;">'
            +'<div class="progressbar-text" style="width: 150px; height: 20px; line-height: 20px;">'+value+'%</div>'
            +'</div>';
        return htmlstr;
    }

    workOrderList.treegrid({
        frozenColumns:[[
            {field:'ck',checkbox:true},
            {field:'iWorkOrderId',title:'iWorkOrderId',width:1,hidden:true},
            {field:'sWorkOrderName',title:'工单名称',width:150,align:'left',halign:'center'},
        ]],
        columns:[[
            {field:'sWorkOrderContent',title:'工单内容',width:250,align:'left',halign:'center'},
            {field:'sStaffName',title:'执行人',width:100,align:'left',halign:'center'},
            {field:'iLevel',title:'工单等级',width:80,align:'center',
                formatter: function(value,row,index){
                    if(value =='1'){
                        var str = '<div style = "background-color:#CCCCCC;color: #ffffff;height: 20px">'+workOrderLevels[value]+'</div>'
                        return str;
                    }else if(value =='2'){
                        var str = '<div style = "background-color:#EEEE00;color: #ffffff;height: 20px">'+workOrderLevels[value]+'</div>'
                        return str;
                    }else if(value =='3'){
                        var str = '<div style = "background-color:#ff1200;color: #ffffff;height: 20px">'+workOrderLevels[value]+'</div>'
                        return str;
                    }
                }
            },
            {field:'iWorkOrderStatus',title:'工单状态',width:80,align:'center',
                formatter: function(value,row,index){
                    if(value =='1'){
                       var str = '<div style = "background-color:#CCCCCC;color: #ffffff;height: 20px">'+workOrderStatus[value]+'</div>'
                        return str;
                    }else if(value =='2'){
                        var str = '<div style = "background-color:#6495ED;color: #ffffff;height: 20px">'+workOrderStatus[value]+'</div>'
                        return str;
                    }else if(value =='3'){
                        var str = '<div style = "background-color:#66CDAA;color: #ffffff;height: 20px">'+workOrderStatus[value]+'</div>'
                        return str;;
                    }else if(value =='4'){
                        var str = '<div style = "background-color:#ee0146;color: #ffffff;height: 20px">'+workOrderStatus[value]+'</div>'
                        return str;
                    }
                }
            },
            {field:'dWorkTime',title:'工时',width:60,align:'right',halign:'center'},
            {field:'iProcess',title:'工单进度', width:158,align:'center',
                formatter: progressFormatter
            },
            {field:'sEnclosure',title:'附件', width:158,align:'center',
                formatter: function (value,row,index) {
                console.log(row.iWorkOrderId);
                    if(value){
                        return '<div><a style="cursor:pointer" iWorkorderId="' + row.iWorkOrderId + '" class="showFileTable"> 查看附件</a></div>';
                    }

                }
            },
            {field:'sExplain',title:'退回原因', width:158,align:'center',
                formatter: function(value,row,index){
                    if(value){
                        return value;
                    }else{
                        return '-';
                    }
                }
            },
            {field:'bIfChecked',title:'审核状态', width:90,align:'center',
                formatter: function(value,row,index){
                    if(value==1){
                        var str = '<div style = "background-color:#00ff23;color: #ffffff;height: 20px">已审核</div>'
                        return str;
                    }else{
                        var str = '<div style = "background-color:#CCCCCC;color: #ffffff;height: 20px">未审核</div>'
                        return str;
                    }
                }
            },
            {field:'tFromAt',title:'预计开始时间',width:140,align:'center'},
            {field:'tEndAt',title:'预计完成时间',width:140,align:'center'},
        ]],
        onSelect:function (row) {
            row['_parentId'] = row['iParentId'] ;
            currentWorkOrderId = row['iWorkOrderId'];
            workOrderList.treegrid('expand',currentWorkOrderId);
            $('#bt_list_edit').setButtonEnable('eu');
            $('#bt_list_del').setButtonEnable('eu');
            if((row['iWorkOrderStatus']=='3'||row['iWorkOrderStatus']=='4')&&row['bIfChecked']!=1){
                $('#bt_list_check').setButtonEnable('eu');
            }else{
                $('#bt_list_check').setButtonDisable('eu');
            }

            if(row['sComments']){
              if(row['sComments'].length>0) {
                  $('#bt_comments_look').setButtonEnable('eu');
              }else{
                  $('#bt_comments_look').setButtonDisable('eu');
              }
            }

            var parentObj = workOrderList.treegrid('getParent',currentWorkOrderId);
            if(parentObj!=null){
                if(parentObj['iParentId']==0){
                    $('#bt_list_add').setButtonDisable('eu');
                }
            }else{
                $('#bt_list_add').setButtonEnable('eu');
            }
        },
        onBeforeSelect:function (row) {
            if (currentWorkOrderId==0){
                return true;
            } else {
                if(currentWorkOrderId==row['iWorkOrderId']){
                    workOrderList.treegrid('unselect',currentWorkOrderId);
                    workOrderList.treegrid('collapse',currentWorkOrderId);
                    currentWorkOrderId=0;
                    $('#bt_list_edit').setButtonDisable('eu');
                    $('#bt_list_del').setButtonDisable('eu');
                    $('#bt_list_check').setButtonDisable('eu');
                    $('#bt_comments_look').setButtonDisable('eu');
                    $('#bt_list_add').setButtonEnable('eu');
                    return false;
                }
            }
        },
        onBeforeCheck:function (row) {
            if(currentWorkOrderId==0){
                return true;
            }else {
                if(currentWorkOrderId==row['iWorkOrderId']){
                    workOrderList.treegrid('uncheckRow',currentWorkOrderId);
                    workOrderList.treegrid('collapse',currentWorkOrderId);
                    currentWorkOrderId=0;
                    $('#bt_list_edit').setButtonDisable('eu');
                    $('#bt_list_del').setButtonDisable('eu');
                    $('#bt_list_check').setButtonDisable('eu');
                    $('#bt_comments_look').setButtonDisable('eu');
                    $('#bt_list_add').setButtonEnable('eu');
                    return false;
                }
            }
        },
        onLoadSuccess:function (row, data) {
            function getParent(pid) {
                var obj = workOrderList.treegrid('find',pid);
                if(obj){
                    workOrderList.treegrid('expand',pid);
                    if(obj['iParentId']!=0){
                        workOrderList.treegrid('expand',obj['iParentId']);
                        var parentObj =  workOrderList.treegrid('find',obj['iParentId']);
                        if(parentObj){
                            if(parentObj['iParentId']!=0){
                                getParent(parentObj['iParentId']);
                            }
                        }
                    }
                }
            }
            if (openId) {
                getParent(openId);
                workOrderList.treegrid('select',openId);
            }
            openId = 0;


            $('.showFileTable').click(function () {
                var id = $(this).attr('iWorkorderId');
                window.top.xhTop.showModal({
                    title: '查看附件',
                    content: xhTool.getFrameString('pm/workorder/showFileTable', {iWorkOrderId:id}, 350),
                    size: 'md',
                    width: 800,
                    backClose: false
                });
            });
        }
    });

    //开启或者完成工单
    $($btn_menu.menubutton('options').menu).menu({
        onClick: function (item) {
            //item 的相关属性参见API中的menu
            if(workOrderList.treegrid('getSelections').length==0){
                window.top.xhTop.showError('错误','请选择一个工单');
                return false;
            }
            var status;
            var iWorkOrderId = workOrderList.treegrid('getSelections')[0]['iWorkOrderId'];
            openId = workOrderList.treegrid('getSelections')[0]['iWorkOrderId'];
            var process = workOrderList.treegrid('getSelections')[0]['iProcess'];
            var childnum = workOrderList.treegrid('getChildren',iWorkOrderId);
            if(item.text == '开始'){
                status = 2;
            }else if(item.text == '完成'){
                if(childnum.length>0&&process!=100){
                    window.top.xhTop.showError('错误','还有子工单未完成');
                    return false;
                }
                status = 3;
            } else if(item.text == '退回'){
                status = 4;
            }
            if (status==2||status==3) {
                $.ajax({
                    url:moduleUrl+'workorder/alterStatus',
                    data:{iWorkOrderId:iWorkOrderId,iWorkOrderStatus:status},
                    type:'POST',
                    success:function (data) {
                        window.top.xhTop.showSuccess(
                            data.msg
                        );
                        workOrderList.treegrid('reload');
                    },
                    error:function (data) {
                        window.top.xhTop.showError(
                            data.responseJSON.error,
                            data.responseJSON.msg
                        );
                    }
                });
            } else {
                window.top.swal({
                    showCancelButton: true,
                    confirmButtonText: '确认',
                    cancelButtonText: '取消',
                    showLoaderOnConfirm: true,
                    allowOutsideClick: false,
                    title: '备注',
                    input: 'textarea',
                    preConfirm: function(explain) {
                        return new Promise(function (resolve, reject) {
                            if(!explain){
                                reject('说明不能为空！');
                            }
                            else if(explain.length > 100) {
                                reject('说明文字超长！');
                            }
                            else {
                                $.ajax({
                                    url:moduleUrl+'workOrder/alterStatus',
                                    data:{iWorkOrderId:iWorkOrderId,iWorkOrderStatus:status,sExplain:explain},
                                    type:'POST',
                                    success:function (data) {
                                        window.top.xhTop.showSuccess(
                                            data.msg
                                        );
                                        window.top.xhTop.getActiveFrame().workOrderList.treegrid('reload');
                                    },
                                    error:function (data) {
                                        window.top.xhTop.showError(
                                            data.responseJSON.error,
                                            data.responseJSON.msg
                                        );
                                    }
                                });
                            }
                        })
                    }
                }).catch(swal.noop);
            }
        }
    });

    $('#bt_list_search').click(function () {
        var status=$('#workorderstatus').val();
        var level=$('#workorderlevel').val();
        var woname = $('#woname').getElementValue();//获取input值
        workOrderList.treegrid('load',{status:status,level:level,sWorkOrderName:woname});
    });




    $('#bt_list_add').click(function () {
        var obj=workOrderList.treegrid('getSelections')[0];
        if (obj!=undefined) {
            var iWorkOrderId = obj['iWorkOrderId'];
            var parentObj = workOrderList.treegrid('getParent',iWorkOrderId);
            if(parentObj){
                if(parentObj['iWorkOrderStatus']==3||parentObj['iWorkOrderStatus']==4){
                    window.top.xhTop.showError('错误','工单已完成或已关闭');
                    return false;
                }
                if(parentObj['iParentId']==0){
                    return false;
                }
            }
            openId = obj['iWorkOrderId'];
            var title = '新建工单 -'+obj['sWorkOrderName']
            window.top.xhTop.showModal({
                title:title,
                content: '<iframe src = "'+moduleUrl+'workorder/workOrderForm?ifNew=1&iParentId='+obj['iWorkOrderId']+'"  style="width: 100%;;border-style: none;padding: 0px;height: 500px;overflow: scroll"></iframe>',
                button:'提交',
                width:850,
                backClose: false

            });
        } else {
            window.top.xhTop.showModal({
                title:'新建工单',
                content: '<iframe src="'+moduleUrl+'workorder/workOrderForm?ifNew=1'+ ' " style="width: 100%;;border-style: none;padding: 0px;height: 500px"  scrolling = "yes"></iframe>',
                button:'提交',
                width:850,
                backClose: false
            });
        }
    });


    $('#bt_list_del').click(function () {
        var obj=workOrderList.treegrid('getSelections')[0];
        if(!obj) return false;
        myWindow.initPopUp({title: '确认删除', text: '确定要删除该工单吗?'},function () {
            $.ajax({
                url:moduleUrl+'workorder/delWorkOrderById',
                data:{iWorkOrderId:obj['iWorkOrderId']},
                type:'POST',
                success:function (data) {
                    window.top.xhTop.showSuccess(
                        data.msg
                    );
                    workOrderList.treegrid('clearSelections');
                    workOrderList.treegrid('reload');
                },
                error:function (data) {
                    window.top.xhTop.showError(
                        data.responseJSON.error,
                        data.responseJSON.msg
                    );
                }
            });
        })

    });

    //查看审核附言
    $('#bt_comments_look').click(function () {
        var obj=workOrderList.treegrid('getSelections')[0];
        if(!obj) return false;
        if(obj['bIfChecked']==1){
            if(obj['sComments']){
                var sComments =  eval('(' + obj['sComments'] + ')');
            }else{
                var sComments =  '附言为空';
            }
            var content = '<span style="font-size: 12px;color: #316AC5">审核人:'+sComments.uname+'</span><br>'+sComments.sComments+'<br><span style="font-size: 12px">审核时间:'+sComments.date+'</span>';
        }else{
            return false;
        }
        window.top.xhTop.showModal({
            title:'审核附言',
            content:content,
            button: true,
            backClose: false
        });
    })

    /////////////////////////////////////////////////////////

    $('#bt_list_edit').click(function () {  //编辑
        if(xhExtra.buttonDisabled($(this))){
            return false;
        }
        var workOrderObj = workOrderList.treegrid('getSelections')[0];
        if(workOrderObj){
            if(workOrderObj['iWorkOrderStatus']==3||workOrderObj['iWorkOrderStatus']==4){
                window.top.xhTop.showError('错误','工单已完成或已关闭');
                return false;
            }
            // var parentName = parentObj['sWorkOrderName'];
        }
        var iWorkOrderId = workOrderObj['iWorkOrderId'];
        var parentObj = workOrderList.treegrid('getParent',iWorkOrderId);
        if(parentObj){
            if(parentObj['iWorkOrderStatus']==3||parentObj['iWorkOrderStatus']==4){
                window.top.xhTop.showError('错误','父工单已完成或已关闭');
                return false;
            }
            var parentName = parentObj['sWorkOrderName'];
        }
        if(parentName){
            var title = '编辑工单 -'+parentName;
        }else{
            var title = '编辑工单';
        }

        var id=workOrderObj['iWorkOrderId'];
        window.top.xhTop.showModal({
            title:title,
            content: '<iframe src="'+moduleUrl+'workorder/workOrderForm?iWorkOrderId='+id+'"  style="width: 100%;border-style: none;padding: 0px;height: 500px"  scrolling="yes"></iframe>',
            button:'提交',
            backClose: false,
            width:850,
        });
    });

//审核订单

    $('#bt_list_check').click(function () {  //审核
        if(xhExtra.buttonDisabled($(this))){
            return false;
        }
        var workOrderObj = workOrderList.treegrid('getSelections')[0];
        if(workOrderObj['iWorkOrderStatus']!='3'&&workOrderObj['iWorkOrderStatus']!='4'){
            return false;
        }
        var iWorkOrderId = workOrderObj['iWorkOrderId'];
        window.top.swal({
            showCancelButton: true,
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            showLoaderOnConfirm: true,
            allowOutsideClick: false,
            title: '审核',
            input: 'textarea',
            preConfirm: function(sComments) {
                return new Promise(function (resolve, reject) {
                    if(!sComments){
                        reject('说明不能为空！');
                    }else if(sComments.length > 100) {
                        reject('说明文字超长！');
                    }else{
                        $.ajax({
                            url: moduleUrl + 'workOrder/checkWorkOrder',
                            data: {iWorkOrderId: iWorkOrderId,sComments:sComments},
                            type: 'POST',
                            success: function (data) {
                                window.top.xhTop.showSuccess(
                                    data.msg
                                );
                                window.top.xhTop.getActiveFrame().workOrderList.treegrid('reload');
                            },
                            error: function (data) {
                                window.top.xhTop.showError(
                                    data.responseJSON.error,
                                    data.responseJSON.msg
                                );
                            }
                        });
                    }
                }).catch(swal.noop);
            }
        });
    });
});

